import { Injectable } from '@nestjs/common';
import { SaveMenuDto } from './dto/menu.dto';
import { FindManyOptions } from 'typeorm';
import { Menu } from './entities/menu.entity';
import { Admin } from '../admin/entities/admin.entity';

@Injectable()
export class MenuService {
  constructor() {}

  async save(saveDto: SaveMenuDto) {
    return await Menu.save(Menu.create(saveDto));
  }

  async find(options?: FindManyOptions<Menu>) {
    return await Menu.find(options);
  }

  async findByAdmin(adminId: string) {
    const admin = await Admin.findOne({
      where: { id: adminId },
      relations: {
        roles: {
          menus: true,
        },
      },
    });
    const menuMap = new Map();
    admin?.roles.forEach((role) => {
      role?.menus.forEach((menu) => {
        menuMap.set(menu.id, menu);
      });
    });
    return Array.from(menuMap.values());
  }

  async delete(ids: string[]) {
    return await Menu.delete(ids);
  }
}
